package com.jn.okhttp.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.jn.okhttp.common.WeakRrfHandler;
import com.jn.okhttp.contract.FoodContract;
import com.jn.okhttp.entity.FoodEntity;
import com.jn.okhttp.utils.LogUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FoodPresenter implements FoodContract.IFoodPresenter {

   public static final int HTTP_SUCCESS = 0;
   public static final int HTTP_FAIL = 1;

   private FoodContract.IFoodView mMainView;
   private Context mContext;
   private OkHttpClient mClient;

   public FoodPresenter(FoodContract.IFoodView mMainView, Context mContext) {
      this.mMainView = mMainView;
      this.mContext = mContext;
      mClient = new OkHttpClient();
   }

   @Override
   public void getData(String keyWord) {//get方式异步请求
      Request request = new Request.Builder()
              .url("https://shanhe.kim/api/za/calories.php?food=" + keyWord)
              //.get()
              .build();
      Call call = mClient.newCall(request);
      call.enqueue(new Callback() {
         @Override
         public void onFailure(@NonNull Call call, @NonNull IOException e) {
            LogUtils.d("asdf", "onFailure");
         }

         @Override
         public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            String body = response.body().string();
            String url = call.request().url().toString();
            LogUtils.d("asdf", "url : " + url);
            LogUtils.d("asdf", "onResponse : " + body);
            Message message = Message.obtain();
            message.obj = new String[] {body, url};
            message.what = HTTP_SUCCESS;
            mHandler.sendMessage(message);
         }
      });
   }

   WeakRrfHandler<FoodPresenter> mHandler = new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
      @Override
      public boolean handleMessage(@NonNull Message msg) {
         int result = msg.what;
         switch (result) {
            case HTTP_SUCCESS:
               String[] data = (String[]) msg.obj;
               if (data == null || data.length < 2) {
                  return false;
               }
               String jsonStr = data[0];
               Gson gson = new Gson();
               FoodEntity foodEntity = gson.fromJson(jsonStr, FoodEntity.class);
               if (mMainView != null) {
                  mMainView.showData(foodEntity);
               }
               break;
            case HTTP_FAIL:
               break;
         }
         return false;
      }
   });
}
